package Interview.Amazon;

import java.util.HashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.Set;

import scala.Int;

/**
 * @author leiwenkang <leiwenkang@kuaishou.com>
 * Created on 2022-08-07
 */
public class Test06贪吃蛇 {
    private LinkedList<Pos> snake;
    private Set<Pos> boardSet;
    private int[][] food;
    private int width;
    private int height;
    private int score;


    public Test06贪吃蛇(int width, int height, int[][] food) {
        this.width = width;
        this.height = height;
        this.food = food;
        Pos pos = new Pos(0, 0);
        snake = new LinkedList<>();
        snake.add(pos);
        boardSet = new HashSet<>();
        boardSet.add(pos);
    }

    public int remove(Direction direction) {
        Pos next = snake.getFirst();
        switch (direction) {
            case UP:
                next.y++;
                break;
            case DOWN:
                next.y--;
                break;
            case LEFT:
                next.x--;
                break;
            case RIGHT:
                next.x++;
            default:
                return -1;
        }

        if (checkOver(next)) {
            return -1;
        }

        if (eatFood(next)) {
            snake.addFirst(next);
            boardSet.add(next);
            score++;
            return score;
        }
        boardSet.remove(snake.getLast());
        snake.removeLast();

        if (boardSet.contains(next)) {
            return -1;
        }

        snake.addFirst(next);
        boardSet.add(next);

        return score;
    }

    public boolean checkOver(Pos pos) {
        if (pos.x < 0 || pos.x >= width || pos.y < 0 || pos.y >= height) {
            return true;
        }

        return false;
    }

    public boolean eatFood(Pos pos) {
        if (score >= food.length) {
            return false;
        }

        if (pos.x == food[score][0] && pos.x == food[score][1]) {
            return true;
        }

        return false;
    }


}

class Pos {
    int x;
    int y;

    public Pos(int x, int y) {
        this.x = x;
        this.y = y;
    }

    @Override
    public String toString() {
        return "Pos{" +
                "x=" + x +
                ", y=" + y +
                '}';
    }
}

enum Direction {
    UP,
    DOWN,
    LEFT,
    RIGHT;
}
